package com.begye.smartloan.apptest.renzheng.selfie

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.AtRenZhengSelfieBinding
import com.begye.smartloan.apptest.fangkuanzhong.FangKuanZhongActivity
import com.begye.smartloan.apptest.gongong.YongHuLiuChengViewModel
import com.begye.smartloan.apptest.homeadsource.HomeAdSourceActivity
import com.begye.smartloan.apptest.homebefore.HomeBeforeActivity
import com.begye.smartloan.apptest.huankuan.HuanKuanActivity
import com.begye.smartloan.apptest.jujue.JuJueActivity
import com.begye.smartloan.apptest.kefu.KeFuDialogFragment
import com.begye.smartloan.apptest.renzheng.RenZhengActivity
import com.begye.smartloan.apptest.renzheng.alldone.RenZhengAllDoneActivity
import com.begye.smartloan.apptest.renzheng.bangka.RenZhengBangKaActivity
import com.begye.smartloan.apptest.renzheng.document.RenZhengDocumentActivity
import com.begye.smartloan.apptest.renzheng.lianxiren.RenZhengLianXiRenActivity
import com.begye.smartloan.apptest.shenhezhong.ShenHeZhongActivity
import com.begye.smartloan.apptest.tool.LoginTool
import com.begye.smartloan.apptest.tool.PageTagTool
import com.begye.smartloan.apptest.tool.addTouch
import com.util.utillib.extend.IntentFlagMode
import com.util.utillib.extend.toNextActivity
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog

class RenZhengSelfieActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var _binding: AtRenZhengSelfieBinding

    private val _renZhengSelfieViewModel by lazy {
        ViewModelProvider(this)[RenZhengSelfieViewModel::class.java]
    }

    private val _yongHuLiuChengViewModel by lazy {
        ViewModelProvider(this)[YongHuLiuChengViewModel::class.java]
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        // 关联布局
        _binding = AtRenZhengSelfieBinding.inflate(layoutInflater)
        setContentView(_binding.root)

        configYongHuLiuChengState()
        configUIState()
        configUIEvent()
    }

    private fun configYongHuLiuChengState() {

        _yongHuLiuChengViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onHasOrderStatusLiveData.observe(this) {
            it?.let { result ->
                when (result) {
                    PageTagTool.dai_huan_kuan -> {
                        toNextActivity(
                            activity = HuanKuanActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.fang_kuan_zhong -> {
                        toNextActivity(
                            activity = FangKuanZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.shen_he_zhone -> {
                        toNextActivity(
                            activity = ShenHeZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.ju_jue -> {
                        toNextActivity(
                            activity = JuJueActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }
                }
            }
        }

        _yongHuLiuChengViewModel.onDoingRenZhengPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingLianXiRenPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengLianXiRenActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingBangKaFrPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengBangKaActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingDocumentPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengDocumentActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onAllDoneLiveData.observe(this) {
            if (it.isNotBlank()) {
                // to shen qing ye
                toNextActivity(
                    activity = RenZhengAllDoneActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP,
                    params = hashMapOf<String, String>().apply {
                        put("titles", it)
                    }
                )
            }
        }
    }


    private fun configUIState() {

        _renZhengSelfieViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _renZhengSelfieViewModel.onSaveSelfieSuccessStateLiveData.observe(this) {
            _yongHuLiuChengViewModel.requestYongHuLiuCheng()
        }
    }

    private fun configUIEvent() {

        _binding.atRenZhengNav.initConfig(
            text = getString(R.string.fill_text_53),
            textColor = "#000000",
            leftResId = R.drawable.dres_39,
            rightResId = R.drawable.dres_38
        ) {
            if (0 == it) {
                if (LoginTool.filterAdType()) {
                    toNextActivity(
                        activity = HomeAdSourceActivity::class.java,
                        mode = IntentFlagMode.SINGLE_TOP
                    )
                } else {
                    toNextActivity(
                        activity = HomeBeforeActivity::class.java,
                        mode = IntentFlagMode.SINGLE_TOP
                    )
                }
            } else if (1 == it) {
                val dialog = KeFuDialogFragment()
                dialog.showNow(supportFragmentManager, "kefu")
            }
        }

        _binding.face.setOnClickListener {
            //
            addTouch(type = "ren_zheng_selfie_start_click")

            toSelfieCaptureActivity()
        }
        _binding.result.setOnClickListener {
            //
            addTouch(type = "ren_zheng_selfie_start_click")

            toSelfieCaptureActivity()
        }
        _binding.save.setOnClickListener {
            if (_renZhengSelfieViewModel.canSubmit()) {
                _renZhengSelfieViewModel.requestSaveSelfie()
            } else {
                toSelfieCaptureActivity()
            }

            //
            addTouch(type = "ren_zheng_selfie_commit_click")
        }
    }

    /**
     * 请求相机权限
     */
    private fun askCameraPermission(): Boolean {
        val list = mutableListOf(android.Manifest.permission.CAMERA)
        if (checkPermissionsGranted(list)) {
            return false
        }
        // 未同意权限
        EasyPermissions.requestPermissions(
            this,
            getString(R.string.disclosure_text_11),
            100,
            *(list.toTypedArray())
        )
        return true
    }

    /**
     * 检查权限是否同意
     */
    private fun checkPermissionsGranted(permissionList: List<String>): Boolean {
        val isNotAllGranted = permissionList.any {
            PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, it)
        }
        return !isNotAllGranted
    }

    // ------> EasyPermissions <------
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        requestPermission()
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            askCameraPermission()
        } else if (requestCode == RenZhengSelfieCaptureActivity.REQUEST_CODE_SELFIE_CAPTURE) {
            if (resultCode == RESULT_OK) {
                val imageOutputPath = data?.getStringExtra("path")
                // 更新页面
                _renZhengSelfieViewModel.handleTakePictureResult(
                    result = imageOutputPath,
                    onConversionCompleted = { _, bitmap, _ ->
                        updateImagePathResult(bitmap)
                    },
                    onUploadCompleted = { _, url, position ->
                        updateImageUrlResult(url)
                    })
            }
        }
    }

    private fun updateImagePathResult(bitmap: Bitmap?) {
        if (bitmap != null) {
            _binding.face.visibility = View.GONE
            _binding.resultBg.visibility = View.VISIBLE
            _binding.result.setImageBitmap(bitmap)
        } else {
            _binding.face.visibility = View.VISIBLE
            _binding.resultBg.visibility = View.GONE
        }
    }

    private fun updateImageUrlResult(url: String?) {
        if (url.isNullOrBlank()) {
            _binding.save.text = getString(R.string.fill_text_54)

            _binding.face.visibility = View.VISIBLE
            _binding.resultBg.visibility = View.GONE

        } else {
            _binding.save.text = getString(R.string.fill_text_57)

            _binding.face.visibility = View.GONE
            _binding.resultBg.visibility = View.VISIBLE
        }
    }

    private fun checkPermission(): Boolean {
        return EasyPermissions.hasPermissions(
            this,
            android.Manifest.permission.CAMERA
        )
    }

    private fun requestPermission() {
        EasyPermissions.requestPermissions(
            this,
            getString(R.string.disclosure_text_11),
            300,
            android.Manifest.permission.CAMERA
        )
    }

    private fun toSelfieCaptureActivity() {
        if (checkPermission()) {
            val intent = Intent(
                this@RenZhengSelfieActivity,
                RenZhengSelfieCaptureActivity::class.java
            )
            startActivityForResult(
                intent,
                RenZhengSelfieCaptureActivity.REQUEST_CODE_SELFIE_CAPTURE
            )

        } else {
            requestPermission()
        }
    }

    override fun onResume() {
        super.onResume()
        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()
        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }
}